const express = require('express');
const router = express.Router();

// 相机相关的API路由
function setupCameraRoutes(pool) {
// 获取物理摄像头列表
router.get('/api/cameras', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM Cameras ORDER BY id');
    res.json(result.rows);
  } catch (error) {
    console.error('获取摄像头列表错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 创建新相机
router.post('/api/cameras', async (req, res) => {
  try {
    const { region, monitor_type, channel_number, point_name, point_code, recognition_model } = req.body;

    // 检查必填字段
    if (!point_name || !channel_number || !point_code) {
      return res.status(400).json({ error: '相机名称、通道号和相机代码为必填项' });
    }

    // 检查相机是否已存在
    const cameraExists = await pool.query(
      'SELECT * FROM Cameras WHERE point_name = $1 OR point_code = $2', 
      [point_name, point_code]
    );

    if (cameraExists.rows.length > 0) {
      return res.status(400).json({ error: '该相机名称或相机代码已存在' });
    }

    // 转换channel_number为整数类型
    const numericChannelNumber = parseInt(channel_number);
    if (isNaN(numericChannelNumber)) {
      return res.status(400).json({ error: '通道号必须是有效的数字' });
    }

    try {
      // 获取当前最大ID
      const maxIdResult = await pool.query('SELECT MAX(id) as max_id FROM Cameras');
      const maxId = maxIdResult.rows[0].max_id || 0;
      const newId = maxId + 1;
      
      const result = await pool.query(
        'INSERT INTO Cameras (id, region, monitor_type, channel_number, point_name, point_code, recognition_model) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, point_name, region, recognition_model, monitor_type, channel_number, point_code',
        [newId, region || '', monitor_type || '', numericChannelNumber, point_name, point_code, recognition_model || '']
      );

      res.status(201).json({
        message: '相机创建成功',
        camera: result.rows[0]
      });
    } catch (dbError) {
      console.error('创建相机错误:', dbError);
      res.status(500).json({ error: '创建相机失败' });
    }
  } catch (error) {
    console.error('相机创建API异常:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 更新相机信息
router.put('/api/cameras/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { point_name, region, recognition_model, monitor_type, channel_number, point_code } = req.body;
    
    // 检查相机是否存在
    const cameraExists = await pool.query('SELECT * FROM Cameras WHERE id = $1', [id]);
    
    if (cameraExists.rows.length === 0) {
      return res.status(404).json({ error: '相机不存在' });
    }
    
    // 检查是否与其他相机冲突
    if (point_name || point_code) {
      let conflictQuery = 'SELECT * FROM Cameras WHERE id != $1';
      let conflictParams = [id];
      
      if (point_name && point_code) {
        conflictQuery += ' AND (point_name = $2 OR point_code = $3)';
        conflictParams.push(point_name, point_code);
      } else if (point_name) {
        conflictQuery += ' AND point_name = $2';
        conflictParams.push(point_name);
      } else if (point_code) {
        conflictQuery += ' AND point_code = $2';
        conflictParams.push(point_code);
      }
      
      const conflictExists = await pool.query(conflictQuery, conflictParams);
      
      if (conflictExists.rows.length > 0) {
        return res.status(400).json({ error: '该相机名称或相机代码已存在' });
      }
    }
    
    // 更新相机信息
    const result = await pool.query(
      'UPDATE Cameras SET point_name = COALESCE($1, point_name), region = COALESCE($2, region), recognition_model = COALESCE($3, recognition_model), monitor_type = COALESCE($4, monitor_type), channel_number = COALESCE($5, channel_number), point_code = COALESCE($6, point_code) WHERE id = $7 RETURNING id, point_name, region, recognition_model, monitor_type, channel_number, point_code',
      [point_name, region, recognition_model, monitor_type, channel_number, point_code, id]
    );
    
    res.json({
      message: '相机更新成功',
      camera: result.rows[0]
    });
  } catch (error) {
    console.error('更新相机错误:', error);
    res.status(500).json({ error: '更新相机失败' });
  }
});

// 删除相机
router.delete('/api/cameras/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查相机是否存在
    const cameraExists = await pool.query('SELECT * FROM Cameras WHERE id = $1', [id]);
    
    if (cameraExists.rows.length === 0) {
      return res.status(404).json({ error: '相机不存在' });
    }
    
    // 使用事务处理
    const client = await pool.connect();
    try {
      await client.query('BEGIN');
      
      // 先删除与该相机相关的映射关系
      await client.query('DELETE FROM Channels WHERE camera_id = $1', [id]);
      
      // 删除相机
      await client.query('DELETE FROM Cameras WHERE id = $1', [id]);
      
      await client.query('COMMIT');
      
      res.json({
        message: '相机删除成功',
        id: id
      });
    } catch (transactionError) {
      await client.query('ROLLBACK');
      throw transactionError;
    } finally {
      client.release();
    }
  } catch (error) {
    console.error('删除相机错误:', error);
    res.status(500).json({ error: '删除相机失败' });
  }
});

  return router;
}

module.exports = setupCameraRoutes;